<template>
  <div class="role-container app-container">
    <el-row>
      <el-col :span="12">
        <el-button
          size="small"
          type="primary"
          @click="handleAddDialog"
        >新增</el-button>
      </el-col>
    </el-row>
    <CommonTable
      class="pagination-container"
      :columns="columns"
      :data-source="tableData"
      :options="options"
      :fetch="fetchTableData"
      :pagination="pagination"
      @row-click="handleRowClick"
      @selection-change="handleSelectionChange"
    />
    <el-dialog
      :title="formOptions.title"
      :visible.sync="formOptions.visible"
      width="30%"
      center
      @closed="closeDialog"
    >
      <el-form ref="formRef" status-icon :rules="rules" :model="formData" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名:" prop="role_name">
              <el-input v-model="formData.role_name" placeholder="请输入角色名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色码:" prop="role_code">
              <el-input v-model="formData.role_code" placeholder="请输入角色码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色描述:" prop="role_desc">
              <el-input v-model="formData.role_desc" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formOptions.visible = false">取 消</el-button>
        <el-button v-if="formOptions.type === 1" type="primary" @click="_handleAdd('formRef')">新增</el-button>
        <el-button v-if="formOptions.type === 2" type="primary" @click="_handleEdit('formRef')">修改</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogRoleVisible"
      title="菜单授权"
      @close="checkedKeys = []"
    >
      <el-tree
        ref="tree"
        :data="menuList"
        show-checkbox
        default-expand-all
        check-on-click-node
        node-key="id"
        :default-checked-keys="checkedKeys"
        :props="defaultProps"
        @check="check"
      />
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogRoleVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveRoleMenu">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '@/components/Table'
import { getRoles, addRole, getRoleInfo, updateRole, deleteRole } from '@/api/role'
import { getMenus } from '@/api/menu'
import { toTree } from '@/utils'
export default {
  name: 'Role',
  components: {
    CommonTable
  },
  data() {
    return {
      dialogRoleVisible: false,
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      checkedKeys: [], // 已配置的菜单
      checkedMenuIds: [],
      roleId: '',
      boolChecked: false, // 用于判断是否点过菜单选项，确认是否调用过check方法
      treeArr: [
        { id: 1, name: '权限管理', pid: 0 },
        { id: 2, name: '按钮权限', pid: 1 },
        { id: 3, name: '页面权限', pid: 1 },
        { id: 4, name: '指令权限', pid: 1 },
        { id: 5, name: '系统管理', pid: 0 },
        { id: 6, name: '字典管理', pid: 5 },
        { id: 7, name: '用户管理', pid: 5 },
        { id: 8, name: '角色管理', pid: 5 },
        { id: 9, name: '菜单管理', pid: 5 },
        { id: 10, name: '用户角色', pid: 7 },
        { id: 11, name: '菜单设置', pid: 9 }
      ],
      formOptions: {
        visible: false,
        title: '',
        type: 1
      },
      columns: [
        {
          prop: 'id',
          label: '编号',
          width: 60
        },
        {
          prop: 'role_name',
          label: '角色名',
          // render 可以根据你想要渲染的方式渲染
          // jsx 不提供 v-model 指令，若你想要使用，，推荐使用插件 babel-plugin-jsx-v-model
          // jsx https://github.com/vuejs/babel-plugin-transform-vue-jsx
          render: (row, index) => {
            return (
              <span style="'color: #ccc'" onClick={e => this.handleClick(e, row)}>
                {row.role_name}
              </span>
            )
          }
        },
        {
          prop: 'role_code',
          label: '角色码'
        },
        {
          prop: 'role_desc',
          label: '角色描述'
        },
        {
          prop: 'created_at',
          label: '创建时间'
        },
        {
          button: true,
          label: '操作',
          group: [
            {
              // you can props => type size icon disabled plain
              name: '编辑',
              type: 'warning',
              icon: 'el-icon-edit',
              plain: true,
              onClick: (row, index) => {
                // 箭头函数写法的 this 代表 Vue 实例
                this.handleEditDialog(row, index)
              }
            },
            {
              // you can props => type size icon disabled plain
              name: '权限',
              type: 'success',
              icon: 'el-icon-lock',
              plain: true,
              onClick: (row, index) => {
                // 箭头函数写法的 this 代表 Vue 实例
                this.handleRuleDialog(row, index)
              }
            },
            {
              name: '删除',
              type: 'danger',
              icon: 'el-icon-delete',
              disabled: false,
              onClick: (row) => {
                // 这种写法的 this 代表 group 里的对象
                this._handleDel(row)
                console.log(this)
                this.disabled = true
              }
            }
          ]
        }
      ],
      tableData: [],
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 15
      },
      options: {
        mutiSelect: true,
        index: true, // 显示序号， 多选则 mutiSelect
        loading: true, // 表格动画
        initTable: true // 是否一挂载就加载数据
      },
      rules: {
        role_name: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        role_code: [
          { required: true, message: '请输入角色码', trigger: 'blur' }
        ]
      },
      formData: {
        role_name: '',
        role_desc: '',
        role_code: ''
      }
    }
  },
  methods: {
    handleClick(e, row) {
      // transform-vue-jsx 的nativeOnClick 失效 , 所以采用 event.cancelBubble 控制点击事件的冒泡... 如果点击事件不影响你的点击行事件，可以不传
      e.cancelBubble = true // 停止冒泡，否则会触发 row-click
      console.log(row)
    },
    async getMenusInfo() {
      const { pageIndex } = this.pagination
      const res = await getMenus({ pageIndex, pageSize: 1000 })
      if (res) {
        const list = res.data.data.rows
        this.menuList = toTree(list)
        console.log(this.roleOptions)
      }
    },
    fetchTableData() {
      this.options.loading = true
      getRoles({
        pageIndex: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize
      })
        .then(res => {
          const { rows, count } = res.data.data
          this.tableData = rows
          this.pagination.total = count
          this.options.loading = false
        })
        .catch(error => {
          console.log(error)
          this.options.loading = false
        })
    },
    handleRowClick(row, event, column) {
      // 点击行的事件，同理可以绑定其他事件
      // console.log('click row:', row, event, column)
    },
    handleSelectionChange(selection) {
      console.log(selection)
    },
    handleAddDialog() {
      this.resetForm('formData')
      this.formOptions.visible = true
      this.formOptions.title = '新增角色'
      this.formOptions.type = 1
      this.formData = {}
    },
    async handleEditDialog(row, index) {
      this.resetForm('formData')
      this.formOptions.visible = true
      this.formOptions.title = '修改角色信息'
      this.formOptions.type = 2
      this.formData = {}
      const res = await getRoleInfo({ id: row.role_id })
      if (res.data) {
        this.formData = res.data.data
      }
    },
    _handleDel(row) {
      this.$confirm(`此操作将永久删除${row.role_name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteRole({ id: row.role_id })
        console.log(res)
        if (res) {
          this.$message({
            type: 'success',
            message: res.data.message
          })
          this.fetchTableData()
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    _handleAdd(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const res = await addRole(this.formData)
          if (res.data) {
            this.$message.success(res.data.message)
            this.formOptions.visible = false
            this.fetchTableData()
          } else {
            this.$message.error(res.data.message)
          }
        } else {
          return false
        }
      })
    },
    _handleEdit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const res = await updateRole(this.formData)
          console.log(res)
          if (res.data) {
            this.$message.success(res.data.message)
            this.formOptions.visible = false
            this.fetchTableData()
          } else {
            this.$message.error(res.data.message)
          }
        } else {
          return false
        }
      })
    },
    closeDialog() {
      this.formData = {}
    },
    handleClose() {},
    resetForm(formName) {
      // console.log(formName);
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    check(menuData, checkedData) {
      this.boolChecked = true
      this.checkedMenuIds = checkedData.checkedKeys.concat(
        checkedData.halfCheckedKeys
      )
    },
    handleRuleDialog(row) {
      console.log(row)
      this.getMenusInfo()
      this.dialogRoleVisible = !this.dialogRoleVisible
    },
    saveRoleMenu() {
      console.log(this.boolChecked)
      console.log(this.checkedMenuIds)
      if (!this.boolChecked) {
        this.dialogRoleVisible = false
        return
      }
      const param = {
        menuIds: this.checkedMenuIds.join(','),
        roleId: this.roleId
      }
      console.log(param)
      this.$message({
        type: 'success',
        message: '保存成功!'
      })
      this.roleId = ''
      this.checkedMenuIds = []
      this.dialogRoleVisible = false
    },
    handleNodeClick(data) {
      console.log(data)
    },
    handleCheckChange(data) {
      // console.log(data);
    },
    onChange(e) {}
  }
}
</script>
